package com.example.configserver.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * 处理配置文件中文乱码问题
 * @date 2019-12-18
 * @TODO 最终还是没解决
 */
@Slf4j
public class MyPropertySourceLoader implements PropertySourceLoader {
    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) {
        Properties properties = this.getProperties(resource);
        return properties.isEmpty() ? Collections.emptyList() : Collections.singletonList(new OriginTrackedMapPropertySource(name, Collections.unmodifiableMap(properties), true));
    }

    private Properties getProperties(Resource resource){
        Properties properties = new Properties();
        try (InputStream inputStream = resource.getInputStream()){
            properties.load(new InputStreamReader(inputStream, "utf-8"));
        } catch (IOException e) {
            log.error("load inputstream failure...", e);
        }
        return properties;
    }
}
